package com.heba.fragment.message;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.adapter.FmPagerAdapter;
import com.heba.bean.ItemShareObject;
import com.heba.bean.ShareObject;
import com.heba.bean.user.UserObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.fragment.BaseFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.message.ItemMessageSendActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.popupwindow.SharePopupWindow;
import com.heba.popupwindow.callback.ShareListener;
import com.heba.utils.IndicatorLineUtil;
import com.loopj.android.http.RequestParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 通讯录页面
 * Created by jason on 2020/1/7.
 */
public class MessageFragment extends BaseFragment {

    private View view_background;

    /**
     * topbar
     */
    private ImageView iv_friend;
    private ImageView iv_share;
    private TextView tv_title;

    /**
     * tablayout
     */
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FmPagerAdapter pagerAdapter;
    private List<String> tabTitles;
    private List<Fragment> fragments = new ArrayList<>();

    private MessageNotificationFragment messageNotificationFragment;
    private MessageMessagesFragment messageMessagesFragment;

    /**
     * 分享彈出框
     */
    private SharePopupWindow sharePopupWindow;
    private ShareObject shareObject;

    private UserObject userObject;   //用戶個人信息

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        Debug.LogError(TAG, "onVisible");
        if (null != tv_title) {
            tv_title.setText(Cfg.Account);
        }
    }

    /**
     * 分享彈出框
     */
    private void initPopupWindow() {
        List<ItemShareObject> shareList1 = new ArrayList<>();
        List<ItemShareObject> shareList2 = new ArrayList<>();

        /**
         * 分享至社交軟件
         */
        int[] ids = {R.drawable.icon_more_share_facebook, R.drawable.icon_more_share_whatsapp, R.drawable.icon_more_share_wechat, R.drawable.icon_more_message};
        String[] contents = this.getResources().getStringArray(R.array.share_contents_friends_invite);
        int[] shareTypes = {CommonConfig.SHARE_TO_FACEBOOK, CommonConfig.SHARE_TO_WHATSAPP, CommonConfig.SHARE_TO_WECHAT, CommonConfig.SHARE_TO_SMS};
        for (int i = 0; i < ids.length; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids[i]);
            shareObject.setShareContent(contents[i]);
            shareObject.setShareType(shareTypes[i]);
            shareList1.add(shareObject);
        }

        sharePopupWindow = new SharePopupWindow(getActivity(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        sharePopupWindow.setShareTitle(getResources().getString(R.string.share_friend_invite));
        sharePopupWindow.hideShareLine();
        sharePopupWindow.setShareList(shareList1, shareList2);

        /**
         * 設置分享監聽
         */
        sharePopupWindow.setOnShareListener(new ShareListener(getContext()) {
            @Override
            public void shareSMS() {
                //短信分享個人名片
                if (null != userObject) {
                    Uri smsToUri = Uri.parse("smsto:");
                    Intent mIntent = new Intent(Intent.ACTION_SENDTO, smsToUri);
//                    mIntent.putExtra("sms_body", String.format(getActivity().getResources().getString(R.string.share_account_to_sms),
//                            userObject.getNickname(), userObject.getLink()));
                    mIntent.putExtra("sms_body", String.format(getActivity().getResources().getString(R.string.share_greenmulu_text1), userObject.getAccount())
                            + "\n" + Cfg.ShareLink);
                    getActivity().startActivity(mIntent);
                }
            }
        });

        sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Debug.LogError(TAG, "onCreateView");
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_message, container, false);
        initFragment();
        initView(view);
        setCustomTabView();
        initPopupWindow();
        getPersonInfoData();
        return view;
    }

    /**
     * initFragment
     */
    private void initFragment() {
        messageNotificationFragment = new MessageNotificationFragment();
        messageMessagesFragment = new MessageMessagesFragment();

        fragments.add(messageNotificationFragment);
        fragments.add(messageMessagesFragment);
    }

    /**
     * initView
     *
     * @param view
     */
    private void initView(View view) {
        view_background = view.findViewById(R.id.view_background);
        iv_friend = view.findViewById(R.id.img_diary_write);
        iv_share = view.findViewById(R.id.img_setting);
        tv_title = view.findViewById(R.id.txt_mine_title);
        tabLayout = view.findViewById(R.id.tabLayout);
        viewPager = view.findViewById(R.id.viewPager);

        iv_friend.setImageResource(R.drawable.icon_message_invite);
        iv_share.setImageResource(R.drawable.icon_message_send);
        iv_share.setVisibility(View.INVISIBLE);

        shareObject = new ShareObject();
        tabTitles = new ArrayList<>();

        /**
         * 邀請好友關注
         */
        iv_friend.setOnClickListener(v -> {
            if (null == userObject)
                return;
//            shareObject.setShareTitle(String.format(this.getResources().getString(R.string.share_account_title), userObject.getNickname()));
//            shareObject.setShareContent(String.format(this.getResources().getString(R.string.share_account_content), userObject.getNickname()));
//            shareObject.setShareImageUrl(userObject.getIcon());
//            shareObject.setShareLink(userObject.getLink());
            shareObject.setShareTitle(getActivity().getResources().getString(R.string.app_name));
            shareObject.setShareContent(String.format(getActivity().getResources().getString(R.string.share_greenmulu_text1), Cfg.Account));
            shareObject.setShareImageUrl(Cfg.ShareImageUrl);
            shareObject.setShareLink(Cfg.ShareLink);
            sharePopupWindow.setShareObject(shareObject);
            view_background.setVisibility(View.VISIBLE);
            sharePopupWindow.showAtLocation(iv_friend, Gravity.BOTTOM, 0, 0);
        });

        /**
         * 傳送好友
         */
        iv_share.setOnClickListener(v -> {
            openActivity(ItemMessageSendActivity.class);
        });
    }

    /**
     * 添加tab标题
     */
    private void addTabTitles() {
        tabTitles.clear();
        tabTitles.add(getActivity().getResources().getString(R.string.message_notification));
        tabTitles.add(getActivity().getResources().getString(R.string.message_messages));
    }

    /**
     * 设置自定义tab
     */
    private void setCustomTabView() {

        /**
         * 添加title文字
         */
        addTabTitles();

        /**
         * 添加tab
         */
        for (int i = 0; i < tabTitles.size(); i++) {
            tabLayout.addTab(tabLayout.newTab());
        }

        /**
         * 关联viewpager,设置adapter
         */
        tabLayout.setupWithViewPager(viewPager, false);
        pagerAdapter = new FmPagerAdapter(fragments, getChildFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(1);

        /**
         * 设置tab文字,必须在关联viewpager之后设置，否则文字不显示
         */
        for (int i = 0; i < tabTitles.size(); i++) {
            tabLayout.getTabAt(i).setText(tabTitles.get(i));
        }

        /**
         * 设置指示线长度间隔(单位dp)
         */
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                IndicatorLineUtil.setIndicator(tabLayout, 0, 0);
            }
        });
    }

    /**
     * 更新信息
     */
    private void updateInfo(UserObject object) {
        //保存account
        Cfg.change("Account", object.getAccount());
        Cfg.save();
        tv_title.setText(Cfg.Account);
    }

    /**
     * 獲取用戶個人信息數據
     */
    private void getPersonInfoData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("BuddyUserID", Cfg.UserID);
        client.get(Cfg.BaseUrl + "/User/GetBuddyInfo", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response.trim()).getJSONObject("Result");
                            userObject = new Gson().fromJson(jsonObject.toString(), UserObject.class);

                            if (null != userObject) {
                                updateInfo(userObject);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收事件
         */
        if (event.getEvent().equals(CommonConfig.NOTIFICATION_REFRESH)) {
            if (null != tabLayout && tabLayout.getTabCount() > 0) {
                tabLayout.getTabAt(0).select();
            }
        }
    }
}
